<?php

/**
 * This file is part of Webman AI.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 */

namespace plugin\ai\app\middleware;

use plugin\ai\app\controller\TaskController;
use plugin\ai\app\service\SensitiveWord;
use plugin\ai\app\controller\AudioController;
use plugin\ai\app\controller\ChatController;
use plugin\ai\app\controller\ImageController;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use Webman\Openai\Chat;

class Security implements MiddlewareInterface
{

    /**
     * @var array[] 要检查的控制器和方法
     */
    protected $actions = [
        AudioController::class => [
            'speech'
        ],
        ChatController::class => [
            'completions', 'translate', 'summarize'
        ],
        ImageController::class => [
            'generations'
        ],
        TaskController::class => [
            'imagine', 'action'
        ]
    ];

    /**
     * 安全检查逻辑
     * @param Request $request
     * @param callable $handler
     * @return Response
     */
    public function process(Request $request, callable $handler) : Response
    {
        $controller = $request->controller;
        $action = $request->action;
        if (!in_array($action, $this->actions[$controller] ?? [])) {
            return $handler($request);
        }
        if (!class_exists(Chat::class)) {
            return json(['error' => ['message' => '请安装webman/openai并重启，安装命令为 composer require -W webman/openai']]);
        }
        $version = $request->header('version');
        if ($version && $version != config('plugin.ai.app.version')) {
            return json(['error' => ['message' => 'AI已经升级，请刷新页面继续使用']]);
        }
        $input = $request->all();
        $messages = $input['input'] ?? $input['content'] ?? $input['prompt'] ?? $input['messages'] ?? $input['image']['prompt'] ?? '';
        if (($messages === '' || $messages === []) && $action !== 'action') {
            return json(['error' => ['message' => '缺少输入参数']]);
        }
        if (is_array($messages)) {
            $firstMessage = current($messages);
            $checkMessages = [];
            if ($firstMessage['role'] ?? '' === 'system') {
                $checkMessages = [$firstMessage];
            }
            if (!$checkMessages || count($messages) > 1) {
                $checkMessages[] = array_slice($request->post('messages'), -1);
            }
            $messages = json_encode($checkMessages, JSON_UNESCAPED_UNICODE);
        }
        $sensitiveWords = SensitiveWord::getSetting();
        $words = $sensitiveWords ? explode("\n", $sensitiveWords) : [];
        if (!SensitiveWord::contentSafe($messages, $words)) {
            return json(['error' => ['message' => '出于政策隐私和安全的考虑，我们无法提供相关信息']]);
        }
        return $handler($request);
    }
}